package com.atguigu.msmservice.contoller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import com.mysql.cj.util.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author He Wentao
 * @since 2022/9/16 22:31
 */

@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Resource
    private MsmService msmService;

    @Resource
    RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){

        // 先判断 redis 里面是否有验证码
        String s = redisTemplate.opsForValue().get(phone);
        // 如果有，就直接显示发送成功
        if (!StringUtils.isNullOrEmpty(s)) return R.ok();

        // redis里面获取不到，再生成生成随机数，进行发送
        String fourBitRandom = RandomUtil.getFourBitRandom();

        // 发送短信验证码
        if (msmService.send(fourBitRandom, phone)){
            // 发送成功，就将  手机号<key> 验证码<value> 保存到 redis，并设置有效时间为 一分钟
            redisTemplate.opsForValue().set(phone,fourBitRandom,1, TimeUnit.MINUTES);
            return R.ok();
        }

      return R.error().message("验证码发送失败，请稍后重试");
    }
}
